package top.hidoctor.auscultation.feature.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.tang.user.UserInfoManager;
import com.tang.util.AppUtil;
import com.tang.util.TimeUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import io.reactivex.functions.Consumer;
import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.bean.DictionaryBean;
import top.hidoctor.auscultation.event.AddYangbenEvent;
import top.hidoctor.auscultation.net.c.AddXyContract;
import top.hidoctor.auscultation.net.p.AddXyPresenter;
import top.hidoctor.auscultation.net.req.AddLabelReq;
import top.hidoctor.auscultation.net.req.DictionaryReq;
import top.hidoctor.auscultation.utils.FileInfoUtils;

public class AddYangbenActivity extends BaseActivity implements AddXyContract.View, View.OnClickListener {

    private static final int REQUESTCODE_FROM_ACTIVITY = 1000;
    private static final int REQUESTCODE_FROM_ACTIVITY2 = 2000;
    private SegmentTabLayout tabZhenjing, tabShoushu;
    String[] zhending = {"否", "是"};
    private AddXyPresenter presenter;
    private DictionaryReq req;
    private List<DictionaryBean.ResultBean> positionList = new ArrayList<>();
    private List<DictionaryBean.ResultBean> coordinateList = new ArrayList<>();
    private List<DictionaryBean.ResultBean> siteList = new ArrayList<>();
    private TextView tvYangben, tvBaogao, tvTime, tvTiwei, tvPeihe, tvChangsuo;
    private EditText editBianhao, editShengao, editTizhong, editDiagnose, editClinicInfo, editDescn;
    private Button btnSave;
    private AddLabelReq labelReq;
    private String yanbenId = "";
    private String xinchaoId = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_yangben);
        presenter = new AddXyPresenter(this, this);
        req = new DictionaryReq();
        labelReq = new AddLabelReq();
        initView();
    }

    private void initView() {
        final Toolbar toolbar = findViewById(R.id.toolbar);
        TextView tvTitle = findViewById(R.id.tv_title);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                hideSoft(toolbar);
            }
        });
        tvTitle.setText("新增样本");
        tabZhenjing = findViewById(R.id.tab_zhenjing);
        tabShoushu = findViewById(R.id.tab_shoushu);
        tvYangben = findViewById(R.id.tv_yangben);
        tvBaogao = findViewById(R.id.tv_baogao);
        editBianhao = findViewById(R.id.edit_bianhao);
        tvTime = findViewById(R.id.tv_time);
        editShengao = findViewById(R.id.edit_shengao);
        editTizhong = findViewById(R.id.edit_tizhong);
        editDiagnose = findViewById(R.id.edit_diagnose);
        editClinicInfo = findViewById(R.id.edit_clinicInfo);
        editDescn = findViewById(R.id.edit_descn);
        tvTiwei = findViewById(R.id.tv_tiwei);
        tvPeihe = findViewById(R.id.tv_peihe);
        tvChangsuo = findViewById(R.id.tv_changsuo);
        btnSave = findViewById(R.id.btn_save);
        tabZhenjing.setTabData(zhending);
        tabShoushu.setTabData(zhending);
        tabZhenjing.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                labelReq.setCalm(position + "");
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        tabShoushu.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                labelReq.setOperation(position + "");
            }

            @Override
            public void onTabReselect(int position) {

            }
        });


        req.setGroupCode("SAMPLE_POSITION");
        presenter.getDictionary(req);
        req.setGroupCode("SAMPLE_COORDINATE");
        presenter.getDictionary(req);
        req.setGroupCode("SAMPLE_SITE");
        presenter.getDictionary(req);


        tvYangben.setOnClickListener(this);
        tvBaogao.setOnClickListener(this);
        tvTiwei.setOnClickListener(this);
        tvPeihe.setOnClickListener(this);
        tvChangsuo.setOnClickListener(this);
        tvTime.setOnClickListener(this);
        btnSave.setOnClickListener(this);


        labelReq.setCalm("0");
        labelReq.setOperation("0");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_yangben:
                if (!AppUtil.isFastClick()) {
                    new RxPermissions(this).request(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        openSystemFile(REQUESTCODE_FROM_ACTIVITY);
                                    } else {
                                        //只要有一个权限被拒绝，就会执行
                                        showToast("权限被禁止，无法打开手机内部储存");
                                    }

                                }
                            });
                }

                break;
            case R.id.tv_baogao:
                if (!AppUtil.isFastClick()) {
                    new RxPermissions(this).request(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        openSystemFile(REQUESTCODE_FROM_ACTIVITY2);
                                    } else {
                                        //只要有一个权限被拒绝，就会执行
                                        showToast("权限被禁止，无法打开手机内部储存");
                                    }

                                }
                            });
                }
                break;
            case R.id.tv_time:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tvTime);
                    showTimePick(1);
                }
                break;

            case R.id.tv_tiwei:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tvTiwei);
                    showPick(1);

                }
                break;
            case R.id.tv_peihe:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tvPeihe);
                    showPick(2);
                }
                break;
            case R.id.tv_changsuo:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tvChangsuo);
                    showPick(3);
                }
                break;
            case R.id.btn_save:
                String yangben = tvYangben.getText().toString().trim();
                String baoao = tvBaogao.getText().toString().trim();
                String biaohao = editBianhao.getText().toString().trim();
                String time = tvTime.getText().toString().trim();
//                String brithday = tvBrithday.getText().toString().trim();
                String shengao = editShengao.getText().toString().trim();
                String tizhong = editTizhong.getText().toString().trim();
                String tiwei = tvTiwei.getText().toString().trim();
                String peihe = tvPeihe.getText().toString().trim();
                String changsuo = tvChangsuo.getText().toString().trim();
                String diagnose = editDiagnose.getText().toString().trim();
                String descn = editDescn.getText().toString().trim();
                String clinicInfo = editClinicInfo.getText().toString().trim();

                if (TextUtils.isEmpty(yanbenId)) {
                    showToast("请选择新增样本");
                    return;
                }
                if (TextUtils.isEmpty(time)) {
                    showToast("请选择检查时间");
                    return;
                }
                if (TextUtils.isEmpty(tiwei)) {
                    showToast("请选择体位");
                    return;
                }
                if (TextUtils.isEmpty(peihe)) {
                    showToast("请选择配合程度");
                    return;
                }
                if (TextUtils.isEmpty(changsuo)) {
                    showToast("请选择采集场所");
                    return;
                }
                labelReq.setHospitalId(UserInfoManager.getInstance().getUserInfo().getHospitalId());
                labelReq.setNo(biaohao);
                labelReq.setExamineDate(time + " 00:00:00");
                labelReq.setHeight(shengao);
                labelReq.setWeight(tizhong);
                labelReq.setDiagnose(diagnose);
                labelReq.setClinicInfo(clinicInfo);
                labelReq.setDescn(descn);
                labelReq.setSampleDetail(new AddLabelReq.SampleDetailBean(yanbenId, xinchaoId));
                presenter.addLabel(labelReq);
                break;
        }
    }

    public void openSystemFile(int type) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//打开多个文件
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择文件"), type);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "请 安装文件管理器", Toast.LENGTH_SHORT);
        }
    }

    /**
     * 时间选择
     * @param type
     */
    private void showTimePick(final int type) {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        startDate.set(1900, 0, 1);
        endDate.set(2021, 11, 31);
        TimePickerView timePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (type == 1) {
                    tvTime.setText(TimeUtil.formatTime(date, TimeUtil.Y_M_D));
                } else if (type == 2) {
//                    tvBrithday.setText(TimeUtil.formatTime(date, TimeUtil.Y_M_D));
                }
            }
        })
                .setTitleText(type == 1 ? "检查时间" : "出生年月")
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(15)//滚轮文字大小
                .setSubCalSize(16)
                .setTitleSize(18)//标题文字大小
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setDividerColor(ContextCompat.getColor(this, R.color.blue_main))
                .setSubmitColor(ContextCompat.getColor(this, R.color.blue_main))
                .setCancelColor(ContextCompat.getColor(this, R.color.colorHintText))
                .setTextColorCenter(ContextCompat.getColor(this, R.color.blue_main)) //设置选中项文字颜色
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();

        timePickerView.show();
    }

    /**
     * 选择框
     * @param type
     */
    private void showPick(final int type) {
        final List<String> list = new ArrayList<>();
        if (type == 1) {
            for (int i = 0; i < positionList.size(); i++) {
                list.add(positionList.get(i).getTitle());
            }
        } else if (type == 2) {
            for (int i = 0; i < coordinateList.size(); i++) {
                list.add(coordinateList.get(i).getTitle());
            }
        } else if (type == 3) {
            for (int i = 0; i < siteList.size(); i++) {
                list.add(siteList.get(i).getTitle());
            }
        }
        OptionsPickerView optionsPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (type == 1) {
                    tvTiwei.setText(list.get(options1));
                    labelReq.setPosition(list.get(options1));
                } else if (type == 2) {
                    tvPeihe.setText(list.get(options1));
                    labelReq.setCoordinate(list.get(options1));
                } else if (type == 3) {
                    tvChangsuo.setText(list.get(options1));
                    labelReq.setSite(list.get(options1));
                }
            }
        })
                .setTitleText(type == 1 ? "选择体位" : type == 2 ? "选择配合程度" : type == 3 ? "选择采集场所" : "")
                .setDividerColor(ContextCompat.getColor(this, R.color.blue_main))
                .setTitleSize(18)
                .setContentTextSize(15)
                .setOutSideCancelable(true)
                .setSubmitColor(ContextCompat.getColor(this, R.color.blue_main))
                .setCancelColor(ContextCompat.getColor(this, R.color.colorHintText))
                .setTextColorCenter(ContextCompat.getColor(this, R.color.blue_main)) //设置选中项文字颜色
                .build();
        optionsPicker.setPicker(list);
        optionsPicker.show();
    }

    /**
     * 数据获取
     * @param bean
     */
    @Override
    public void getDictionarySuc(DictionaryBean bean) {
        String groupCode = "";
        if (bean.getResult().size() > 0) {
            groupCode = bean.getResult().get(0).getGroupCode();
        }
        if (groupCode.equals("SAMPLE_POSITION")) {
            positionList.addAll(bean.getResult());
        } else if (groupCode.equals("SAMPLE_COORDINATE")) {
            coordinateList.addAll(bean.getResult());
        } else if (groupCode.equals("SAMPLE_SITE")) {
            siteList.addAll(bean.getResult());
        }
    }

    /**
     * 添加成功回调
     */
    @Override
    public void addLabelSuc() {
        showToast("添加成功");
        finish();
        EventBus.getDefault().post(new AddYangbenEvent());
    }

    /**
     * 获取样本信息回调
     * @param data
     */
    @Override
    public void getYangbenSuc(String data) {
        yanbenId = data;
    }

    /**
     * 获取心超报告回调
     * @param data
     */
    @Override
    public void getXinchaoSuc(String data) {
        xinchaoId = data;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_FROM_ACTIVITY && resultCode == Activity.RESULT_OK) {
            //Get the Uri of the selected file
            if (data.getClipData() != null) {//有选择多个文件
                int count = data.getClipData().getItemCount();
                Log.i("TAG", "url count ：  " + count);
                int currentItem = 0;

                while (currentItem < count) {
                    Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                    String imgpath = FileInfoUtils.getPath(this, imageUri);
                    Log.i("TAG", "url " + imgpath);
                    currentItem = currentItem + 1;
                }

            } else if (data.getData() != null) {//只有一个文件咯
                String path = FileInfoUtils.getPath(this, data.getData());
                Log.i("TAG", "Single image path ---- " + path);
                if (path.contains(".wav")) {
                    String[] list = path.split("/");
                    if (list.length == 0) {
                        return;
                    }
                    String yangben = list[list.length - 1];
                    tvYangben.setText(yangben);
                    presenter.uploadFile(path, 1);
                    editBianhao.setText("循音科技-" + yangben.split(".wav")[0]);
                } else {
                    showToast("请选择wav文件");
                }
            }

        } else if (requestCode == REQUESTCODE_FROM_ACTIVITY2 && resultCode == Activity.RESULT_OK) {
            //Get the Uri of the selected file
            if (data.getClipData() != null) {//有选择多个文件
                int count = data.getClipData().getItemCount();
                Log.i("TAG", "url count ：  " + count);
                int currentItem = 0;

                while (currentItem < count) {
                    Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                    String imgpath = FileInfoUtils.getPath(this, imageUri);
                    Log.i("TAG", "url " + imgpath);
                    currentItem = currentItem + 1;
                }

            } else if (data.getData() != null) {//只有一个文件咯
                String path = FileInfoUtils.getPath(this, data.getData());
                Log.i("TAG", "Single image path ---- " + path);
                if (path.contains(".pdf")) {
                    String[] baogao = path.split("/");
                    if (baogao.length == 0) {
                        return;
                    }
                    tvBaogao.setText(baogao[baogao.length - 1]);
                    presenter.uploadFile(path, 2);
                } else {
                    showToast("请选择pdf文件");
                }
            }

        }
    }

}
